package com.example.day_day_up.filter;

import com.example.day_day_up.config.AppConfig;
import com.example.day_day_up.entity.constants.Constants;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@WebFilter("/*")
public class LoginFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        HttpSession session = request.getSession();

        // 登录状态
        if (session.getAttribute(Constants.USER_KEY) != null) {
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }

        String defaultURI = request.getContextPath();

        // 允许放行的资源
        String requestURI = request.getRequestURI();
        boolean allowed = false;
        for (String suffix : AppConfig.ALLOWED_SUFFIXES) {
            if (requestURI.contains(suffix)) {
                allowed = true;
                break;
            }
        }

        // 放行资源和静态资源
        if (allowed || requestURI.equals(defaultURI + AppConfig.ALLOWED_DEFAULT)) {
            filterChain.doFilter(servletRequest, servletResponse);
        } else {
            if (!requestURI.contains(AppConfig.LOGIN_PAGE)) {
                response.sendRedirect(defaultURI + AppConfig.LOGIN_PAGE);
            }
        }
    }

    @Override
    public void destroy() {
    }
}
